import  time
import functools
from manual_config import Manual_config
from log_help import TraceHelper
from global_variable import Global_share_variable
def  calculate_function_run_time(timeout=0):
    """
    Calculate the running time of the function
    当函数超时 and TRACE 打开时记录
    :param func: the function need to been calculated
    :return:
    """
    def decorator(func):
        if getattr(Manual_config,"TRACE",False) or getattr(Manual_config,"EXCEPTION_AUTO_TRACE",False):
        
            @functools.wraps(func)
            def clocked(*args, **kwargs):
                start = time.time()
                start1 = time.perf_counter()
                result = None
                try:
                    result = func(*args, **kwargs)
                except:
                    setattr(Global_share_variable,"exception_auto_trace_flag",True)
                    
                    end = time.time()
                    end1 = time.perf_counter()
                    r_time = end1 - start1
                    in_parameter = str((args,kwargs))
                    out_parameter = str(result)
                    l2 = TraceHelper(func.__name__)
                    l2.log_exception(transaction_id=getattr(Global_share_variable,"message_id","message_id"), start_time=start, end_time=end, run_time=r_time,
                            in_parameter = in_parameter,out_parameter = out_parameter)

                            
                end = time.time()
                end1 = time.perf_counter()
                r_time = end1 - start1

                in_parameter = str((args,kwargs))
                out_parameter = str(result)
                tag = func.__name__
                if r_time > timeout and getattr(Manual_config,"TRACE",False):
                    '''
                    如果超过指定时间，写入报警日志
                    '''
                    l2 = TraceHelper(tag)
                    # l2.log(transaction_id=kwargs.get('transaction_id',"transaction_id"), start_time=start, end_time=end, run_time=r_time,
                    #         in_parameter = in_parameter,out_parameter = out_parameter)
                    l2.log(transaction_id=getattr(Global_share_variable,"message_id","message_id"), start_time=start, end_time=end, run_time=r_time,
                            in_parameter = in_parameter,out_parameter = out_parameter)
                    # print(func.__name__, r_time)
                    # print(func.__name__,"timeout")
                elif getattr(Manual_config,"EXCEPTION_AUTO_TRACE",False):
                    getattr(Global_share_variable,"trace_queue").put_nowait((tag,
                                                                    getattr(Global_share_variable,"message_id","message_id"),
                                                                    start,
                                                                    end,
                                                                    r_time,
                                                                    in_parameter,
                                                                    out_parameter
                                                                    ))
                return  result
            return clocked

        else:
            @functools.wraps(func)
            def clocked(*args, **kwargs):
                return func(*args, **kwargs)
            return clocked
    return decorator

if __name__ == '__main__':
    @calculate_function_run_time()
    def test(t,*args,**kwargs):
        print("excute...")
        time.sleep(1)
        a = t/0
        return a,args ,kwargs
        
    test("报警0","报警1",a="报警2",c="dfg",transaction_id="258dsewat")
    test(1,2,a="df",c="dfg",transaction_id="258dsewat")
    Global_share_variable.trace_log_print()
    # print(test.__name__)
